package com.wwm.springcloud.authservice.config;

import com.wwm.springcloud.authservice.service.extend.BwDaoAuthenticationProvider;
import com.wwm.springcloud.authservice.common.BwPasswordEncoder;
import com.wwm.springcloud.authservice.service.extend.DbUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.ReflectionSaltSource;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @author wuwanming
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{
    @Autowired
    private DbUserDetailsService userDetailsService;

    /**
     * 请求授权
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http
                .authorizeRequests()
                //放过请求
                .antMatchers("/", "/bwhealthy","/app/*").permitAll()
                .anyRequest().authenticated()
                .and().csrf().disable();
        super.configure(http);
    }

    /**
     * 配置帮助类，以便快速的在应用中创建通用的身份验证功能
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception
    {
        ReflectionSaltSource rss = new ReflectionSaltSource();
        rss.setUserPropertyToUse("salt");

        BwDaoAuthenticationProvider provider = new BwDaoAuthenticationProvider();
        provider.setSaltSource(rss);
        provider.setUserDetailsService(userDetailsService);
        provider.setPasswordEncoder(new BwPasswordEncoder("md5"));

        auth.authenticationProvider(provider);
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
